﻿using System;
using System.ComponentModel;
using System.Globalization;
using System.Resources;
using System.Windows.Forms;
using TSites.GUI.Enums;
using TSites.GUI.Languages;
using TSites.GUI.Properties;
using TSites.Service.Entities;
using VNMessageBox;
using BrightIdeasSoftware;
//using System.Linq;

namespace TSites.GUI
{
	public partial class frmCompany : Form
	{
		public frmCompany()
		{
			InitializeComponent();
		}

		#region Events

		private void frmCompany_Load(object sender, EventArgs e)
		{
			ApplyResource();
			DisplayData();
		}

		private void txtCompanyName_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Enter)
			{
				DisplayData();
			}
		}

		private void txtCompanyName_TextChanged(object sender, EventArgs e)
		{
			string comName = txtCompanyName.Text.Trim();
			ClientNameFilter(comName);
			if (comName.Length != 0 && !picClearClientName.Visible)
			{
				picClearClientName.Visible = true;
			}
			else if (comName.Length == 0 && picClearClientName.Visible)
			{
				picClearClientName.Visible = false;
			}
		}

		private void picClearClientName_Click(object sender, EventArgs e)
		{
			txtCompanyName.Text = string.Empty;
			DisplayData();
		}

		private void btnExport_Click(object sender, EventArgs e)
		{
			OpenExportForm();
		}

		private void btnExcelImport_Click(object sender, EventArgs e)
		{
			frmExcelImport excelImport = new frmExcelImport();
			DialogResult dlgResult = excelImport.ShowDialog();
			if (dlgResult == DialogResult.OK)
			{
				DisplayData();
			}
		}

		private void btnAdd_Click(object sender, EventArgs e)
		{
			AddCompany();
		}

		private void btnUpdate_Click(object sender, EventArgs e)
		{
			UpdateCompany();
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			DeleteCompany();
		}

		#region Object listview

		private void olvClients_FormatRow(object sender, BrightIdeasSoftware.FormatRowEventArgs e)
		{
			e.Item.SubItems[1].Text = (e.DisplayIndex + 1).ToString();
		}

		private void olvClients_SelectedIndexChanged(object sender, EventArgs e)
		{
			Company selectedCompany = (Company)olvClients.SelectedObject;
			if (selectedCompany != null)
			{
				if (!btnUpdate.Enabled)
				{
					btnUpdate.Enabled = btnDelete.Enabled = btnExport.Enabled = true;
				}
			}
			else
			{
				if (btnUpdate.Enabled)
				{
					btnUpdate.Enabled = btnDelete.Enabled = btnExport.Enabled = false;
				}
			}
		}

		private void olvClients_KeyUp(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Delete)
			{
				DeleteCompany();
			}
		}

		private void olvClients_MouseDoubleClick(object sender, MouseEventArgs e)
		{
			OpenExportForm();
		}
		
		#endregion

		#endregion

		#region Methods

		public void ChangeLanguage()
		{
			ApplyResource();

			LANGUAGE language = ConfigurationSingleton.Instance.Language;
			// get data
			string clientName = txtCompanyName.Text.Trim();
			Company[] companies = CompanySingleton.Instance.GetCompanies(clientName, (int)language);
			SetupAutocomplete(companies, language);
			olvClients.Refresh();
		}

		public void ApplyResource()
		{
			CultureInfo culture = CultureInfoFactory.GetInstance();
			ResourceManager rm = new ResourceManager(CultureInfoFactory.BASEDNAME, typeof(frmCompany).Assembly);

			btnAdd.Text = rm.GetString("Add", culture);
			btnUpdate.Text = rm.GetString("Update", culture);
			btnDelete.Text = rm.GetString("Delete", culture);
			btnExport.Text = rm.GetString("Export", culture);
			btnExcelImport.Text = rm.GetString("Import", culture);

			olvColNo.Text = rm.GetString("No", culture);
			olvColTaxCode.Text = rm.GetString("ClientTaxCode", culture);
			olvColName.Text = rm.GetString("ClientName", culture);
			olvColPosition.Text = rm.GetString("ClientPosition", culture);
			olvColRepresentedBy.Text = rm.GetString("ClientRepresentedBy", culture);
			olvColAddress.Text = rm.GetString("ClientAddress", culture);

			olvClients.EmptyListMsg = rm.GetString("ClientEmpty", culture);
			// assign AspectName
			LANGUAGE language = ConfigurationSingleton.Instance.Language;
			if (language == LANGUAGE.Vietnames)
			{
				olvColName.AspectName = "VietnamesName";
				olvColAddress.AspectName = "VietnamesAddress";
				olvColPosition.AspectName = "VietnamesPosition";
			}
			else
			{
				olvColName.AspectName = "EnglishName";
				olvColAddress.AspectName = "EnglishAddress";
				olvColPosition.AspectName = "EnglishPosition";
			}
		}

		private void DisplayData()
		{
			LANGUAGE language = ConfigurationSingleton.Instance.Language;
			
			// get data
			string clientName = txtCompanyName.Text.Trim();
			Company[] companies = CompanySingleton.Instance.GetCompanies(clientName, (int)language);
			SetupAutocomplete(companies, language);
			olvClients.SetObjects(companies);
			CheckConstrain();
		}

		private void AddCompany()
		{
			frmUpdateCompany updCompany = new frmUpdateCompany(ACTION.ADD);
			updCompany.ShowDialog();

			if (updCompany.EffectedRow > 0)
			{
				txtCompanyName.Text = string.Empty;

				// re-display data
				DisplayData();
				olvClients.SelectedObject = updCompany.CompanyInstance;
				olvClients.EnsureVisible(olvClients.SelectedIndex);
			}
		}

		private void UpdateCompany()
		{
			Company client = GetClientObject();
			if (client != null)
			{
				LANGUAGE language = ConfigurationSingleton.Instance.Language;
				string oldClientName = language == LANGUAGE.Vietnames ? client.VietnamesName : client.EnglishName;

				frmUpdateCompany updCompany = new frmUpdateCompany(ACTION.UPDATE, client);
				updCompany.ShowDialog();
				if (updCompany.EffectedRow > 0)
				{
					// re-display data
					DisplayData();
					olvClients.SelectedObject = updCompany.CompanyInstance;
				}
			}
		}

		private void DeleteCompany()
		{
			Company client = GetClientObject();
			if (client != null)
			{
				LANGUAGE language = ConfigurationSingleton.Instance.Language;
				CultureInfo culture = CultureInfoFactory.GetInstance();
				ResourceManager rm = new ResourceManager(CultureInfoFactory.BASEDNAME, typeof(frmCompany).Assembly);
				
				string message, title, clientName;
				clientName = language == LANGUAGE.Vietnames ? client.VietnamesName : client.EnglishName;
				message = string.Format(rm.GetString("ConfirmDeleteMsg", culture), clientName);
				title = rm.GetString("Notice", culture);

				DialogResult dlgResult;
				if (language == LANGUAGE.Vietnames)
				{
					dlgResult = CMessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
				}
				else
				{
					dlgResult = MessageBox.Show(message, title, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
				}

				if (dlgResult == DialogResult.Yes)
				{
					CompanySingleton companySingle = CompanySingleton.Instance;
					int effectedRow;
					try
					{
						effectedRow = companySingle.Remove(client.ID);
					}
					catch (Exception ex)
					{ 
						effectedRow = -1;

						title = rm.GetString("Error", culture);
						if (language == LANGUAGE.Vietnames)
						{
							CMessageBox.Show(ex.StackTrace, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
						else
						{
							MessageBox.Show(ex.StackTrace, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
					}

					if (effectedRow > 0)
					{
						// re-display data
						DisplayData();
					}
					else
					{
						message = string.Format(rm.GetString("ErrorCompanyMsg", culture), rm.GetString("ErrorDelete", culture));
						title = rm.GetString("Error", culture);
						if (language == LANGUAGE.Vietnames)
						{
							CMessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
						else
						{
							MessageBox.Show(message, title, MessageBoxButtons.OK, MessageBoxIcon.Error);
						}
					}
				}
			}
		}

		private void SetupAutocomplete(Company[] companies, LANGUAGE language)
		{
			txtCompanyName.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
			txtCompanyName.AutoCompleteSource = AutoCompleteSource.CustomSource;
			AutoCompleteStringCollection namesCollection = new AutoCompleteStringCollection();
			if (companies != null)
			{
				foreach (Company com in companies)
				{
					namesCollection.Add(language == LANGUAGE.Vietnames ? com.VietnamesName : com.EnglishName);
				}
			}
			txtCompanyName.AutoCompleteCustomSource = namesCollection;
		}

		private Company GetClientObject()
		{
			return (Company)olvClients.SelectedObject;
		}

		private void OpenExportForm()
		{
			Company client = GetClientObject();
			if (client != null)
			{
				new frmExport(client).ShowDialog();
			}
		}

		private void CheckConstrain()
		{
			bool enabled = olvClients.Items.Count > 0 && olvClients.SelectedObject != null;
			if (enabled != btnAdd.Enabled)
			{
				btnUpdate.Enabled = btnDelete.Enabled = btnExport.Enabled = enabled;
			}
		}

		private void ClientNameFilter(string comName)
		{
			TextMatchFilter filter = null;
			if (!string.IsNullOrEmpty(comName))
			{
				filter = TextMatchFilter.Contains(olvClients, comName);
			}

			// Setup a default renderer to draw the filter matches
			if (filter == null)
			{
				olvClients.DefaultRenderer = null;
			}
			else
			{
				olvClients.DefaultRenderer = new HighlightTextRenderer(filter);
				// Uncomment this line to see how the GDI+ rendering looks
				//olvClients.DefaultRenderer = new HighlightTextRenderer { Filter = filter, UseGdiTextRendering = false };
			}

			// Some lists have renderers already installed
			//HighlightTextRenderer highlightingRenderer = olvClients.GetColumn(2).Renderer as HighlightTextRenderer;
			//if (highlightingRenderer != null)
			//{
			//    highlightingRenderer.Filter = filter;
			//}

			olvClients.AdditionalFilter = filter;
			//olvClients.Invalidate();
		}

		#endregion
	}
}
